<template>
  <!-- 公历农历日期选择器 -->
  <div>
    <el-dialog
      title="日期选择"
      :visible.sync="dialogVisible"
      width="480px"
      :show-close="false"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      @open="openedHandle"
    >
      <Calendar :key="calendarKey" ref="calendar" v-model="date" :type.sync="thisType" />
      <span slot="footer" class="dialog-footer">
        <Button @click="cancelHandle">取消</Button>
        <Button type="primary" @click="confrim">确定</Button>
      </span>
    </el-dialog>
    <el-input
      :value="dateStr"
      :disabled="disabled"
      :placeholder="placeholder"
      clearable
      @focus="dialogVisible = true"
      @clear="clearHandle"
    />
  </div>
</template>
<script>
import Calendar from '@/components/Calendar'
import Button from '@/components/Button'
export default {
  name: 'CalendarPickerPane',
  components: {
    Calendar,
    Button
  },
  props: {
    value: {
      type: [String],
      default: ''
    },
    type: {
      type: String,
      default: 'solar'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请选择'
    }
  },
  data() {
    return {
      dialogVisible: false,
      date: '',
      thisType: 'solar',
      calendarKey: 'calendarKey'
    }
  },
  computed: {
    dateStr() {
      if (this.date) {
        if (this.thisType === 'solar') {
          return `${this.date}(公历)`
        } else {
          return `${this.date}(农历)`
        }
      } else {
        return ''
      }
    }
  },
  watch: {
    value: {
      handler: 'updateDate',
      immediate: true
    },
    type: {
      handler: 'updateType',
      immediate: true
    }
  },
  methods: {
    closeDailog() {
      this.dialogVisible = false
    },
    // 确定
    confrim() {
      this.$emit('change', this.date, this.thisType)
      this.$emit('input', this.date)
      this.$emit('update:type', this.thisType)
      this.closeDailog()
    },
    // 取消
    cancelHandle() {
      this.date = this.value
      this.thisType = this.type
      this.closeDailog()
    },
    clearHandle() {
      this.$emit('input', '')
      this.$emit('update:type', '')
    },
    // 更新date
    updateDate() {
      this.date = this.value
    },
    // 更新type
    updateType() {
      if (!this.type) {
        this.thisType = 'solar'
      } else {
        this.thisType = this.type
      }
    },
    // 打开后更新数据
    openedHandle() {
      this.calendarKey = (Math.random() * 0xfffff).toString(16)
    }
  }
}
</script>
<style lang='scss' scoped>
</style>
